package com.codeoss.framework.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import com.codeoss.framework.request.LoginPageRequest;
import com.codeoss.framework.response.LoginPageResponse;
import com.codeoss.framework.service.ILoginPageService;
import com.codeoss.framework.springsecurity.JwtTokenUtil;
import com.codeoss.framework.util.LoginLogUtil;
import com.codeoss.module.res.model.ResUser;
import com.codeoss.module.res.service.IResUserService;

@Service
public class LoginPageService implements ILoginPageService {
	@Autowired
	private PasswordEncoder passwordEncoder;
	@Autowired
	private UserDetailsService userDetailsService;
	@Autowired
	private JwtTokenUtil jwtTokenUtil;
	@Autowired
	private IResUserService resUserService;
	@Autowired
	private LoginLogUtil loginLogUtil;
	@Override
	public LoginPageResponse login(LoginPageRequest request) {
		// TODO Auto-generated method stub
		LoginPageResponse devLoginPageResponse = new LoginPageResponse();
		String username = request.getUsername();
		String password = request.getPassword();
		try {
			UserDetails userDetails = userDetailsService.loadUserByUsername(username);
			if (!passwordEncoder.matches(password, userDetails.getPassword())) {
				throw new BadCredentialsException("密码不正确");
			}
			UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails,
					null, userDetails.getAuthorities());
			SecurityContextHolder.getContext().setAuthentication(authentication);
			String token = jwtTokenUtil.generateToken(userDetails);
			devLoginPageResponse.setToken(token);
		} catch (AuthenticationException e) {
			throw new RuntimeException(e);
		}
		ResUser resUser=resUserService.getResUserByUsername(username);
		if(resUser.getDeveloper()!=null && resUser.getDeveloper()==true) {
		     devLoginPageResponse.setDeveloper(true);
		}
		loginLogUtil.logLogin();
		return devLoginPageResponse;
	}

}
